import axios from 'axios'
import qs from 'qs'

let baseURL = 'http://newsystest.peopleyun.cn'
// let baseURL = 'https://newsysapi.peopleyun.cn/'
// 请求拦截器
axios.interceptors.request.use(
  config => {
    if (config.method === 'post') {
      switch (config.headers['content-type']) {
        case 'application/x-www-form-urlencoded':
          config.data = qs.stringify(config.data, {
            allowDots: true
          })
          break
      }
      switch (config.headers['content-type']) {
        case 'application/json;charset=UTF-8':
          if (
            config.headers['stringfy'] &&
            config.headers['stringfy'] === '0'
          ) {
            config.data = config.data
          } else {
            config.data = JSON.stringify(config.data)
          }
          break
      }
    }
    return config
  },
  error => {
    return Promise.error(error)
  }
)
axios.interceptors.response.use(res => {
  // if (!res.data.status && res.data.message === 'nologin') {
  //   localStorage.setItem('path', window.vm.$router.currentRoute.fullPath)
  //   window.vm.$router.push('/login')
  // }
  return res
})

axios.defaults.withCredentials = true

export default {
  baseURL: baseURL,
  get(url, data, config = {}) {
    if (data && data.http && data.http === 'local') {
      return axios({
        method: 'get',
        url
      })
    } else {
      return axios({
        method: 'get',
        url: baseURL + url,
        params: data,
        ...config
      })
    }
  },
  post(url, data, config = {}) {
    return axios({
      method: 'post',
      url: baseURL + url,
      data: data,
      headers: {
        // 'content-type': 'application/x-www-form-urlencoded',
        'Content-Type': 'application/json;charset=UTF-8'
      },
      ...config
    })
  }
}
